from typing import List

from fastapi import APIRouter, Depends
import json
from sqlalchemy import select, desc, func, distinct
from sqlalchemy.ext.asyncio import AsyncSession
from apis.deps import get_db
from schemas import HostUpdate, HostCreate, HostOut as Host, Result, ResultPlus
from crud import host
from utils import resp_200, IdNotExist
from models import Host as HostModel

router = APIRouter()


@router.post("/create_host", response_model=Result, summary="新增host")
async def create_host(host_in: HostCreate, db: AsyncSession = Depends(get_db)):
    await host.create(db=db, obj_in=host_in)
    return resp_200(msg=f"成功添加host")


@router.get("/", response_model=ResultPlus[Host], summary="查询host列表")
async def get_host(pageIndex: int = 1, pageSize: int = 10, queryName: str = '', projectId: int = 0,
                   db: AsyncSession = Depends(get_db)):
    sql1 = select(HostModel).offset((pageIndex - 1) * pageSize).limit(pageSize).where(
        HostModel.name.like(f'%{queryName}'), HostModel.projectId == projectId).order_by(desc(HostModel.id))
    result1 = await db.execute(sql1)
    host = result1.scalars().all()
    sql2 = select(func.count(distinct(HostModel.id))).where(HostModel.projectId == projectId)
    count = await db.scalar(sql2)
    return resp_200(data={"count": count, "list": host}, msg=f"查询成功")


@router.put('/update_host/{id}', response_model=Result, summary="通过id更新host信息")
async def update_host(id: int, host_in: HostUpdate, db: AsyncSession = Depends(get_db)):
    row = await host.update(db, id, obj_in=host_in)
    return resp_200(msg=f"成功更新host信息")


@router.delete('/delete_host/{id}', response_model=Result, summary="通过id删除host信息")
async def delete_host(id: int, db: AsyncSession = Depends(get_db)):
    row = await host.remove(db, id)
    return resp_200(msg=f"成功删除host信息")


@router.put('/updateStatusHost/{id}', response_model=Result, summary="通过id更新host状态")
async def updateStatusHost(id: int, db: AsyncSession = Depends(get_db)):
    host = await db.get(HostModel, id)
    host.status = not host.status
    await db.commit()
    return resp_200(msg="host状态更新成功")
